<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;text-align: center">
      <el-form :inline="true" :model="query">
<!--        <el-form-item>-->
<!--          <el-input v-model="query.keyword" placeholder="Keyword" style="width:500px"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" v-on:click="search">搜索</el-button>-->
<!--        </el-form-item>-->
        <el-form-item style="float: left;">
          <el-button type="primary" @click="handleAdd" style="width: 120px; height: 40px;float: left;">新增</el-button>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" @click="handleAdd">新增</el-button>-->
        <!--        </el-form-item>-->
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="100">
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.type === 1" style="color: green;">登录等待公告</span>
          <span v-if="scope.row.type === 2" style="color: red;">轮播图公告</span>
          <span v-if="scope.row.type === 3" style="color: #0090ff;">喇叭公告</span>

        </template>
      </el-table-column>
      <el-table-column prop="imgurl" label="喇叭公告/图片" width="300" sortable>
        <template slot-scope="scope">
          <div v-if="scope.row.type === 1 || scope.row.type === 2" class="demo-image__preview">
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.imgurl"
                :preview-src-list="[scope.row.goodsImg]">
            </el-image>
          </div>
          <div v-else>
            {{scope.row.imgurl}}
          </div>
        </template>
      </el-table-column>
            <el-table-column label="操作" width="250">
              <template scope="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--      @size-change 当每页显示条数的值发生改变时会触发-->
      <!--      @current-change 当 当前页的值发生改变时会触发-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float: right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="addForm" >
        <el-form-item label="公告类型" prop="type">
          <template>
            <el-select v-model="saveForm.type" placeholder="请选择" @change="handleTypeChange" >
              <el-option
                  v-for="item in posterType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="商品图片" prop="imgurl" v-if="selectOption == 1 || selectOption == 2">
          <!--          <el-input type="textarea" v-model="saveForm.goodsImg" placeholder="请输入完整的图片url路径"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://8.217.49.47:8082/goods/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="喇叭公告" prop="imgurl" v-if="selectOption == 3">
          <!-- 当 saveForm.type 为 3 时显示这个输入框 -->
          <el-input v-model="saveForm.imgurl" placeholder="请输入喇叭公告"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit('addForm')" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>


export default {
  data() {
    return {
      fileList:[],
      pageInfo: {
        rows: [],
        total: 0
      },
      query: {
        currentPage: 1,
        pageSize: 20,
        keyword: ""
      },
      posterType:[{
        value: '1',
        label: '登录等待'
      }, {
        value: '2',
        label: '轮播图'
      }, {
        value: '3',
        label: '喇叭公告'
      }],

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false, //编辑界面是否显示
      addLoading: false,

      //编辑界面数据
      saveForm: {
        id: null,
        type:'',
        imgurl:'',
      },
      saveFormRules: {
        type: [
          {required: true, message: '请选择公告类型', trigger: 'blur'}
        ],
      },
      selectOption:'',
    }
  },
  methods: {

    handleTypeChange(newValue){
      this.selectOption = newValue;
    },


    handleRemove(file, fileList) {

      this.$http.post('/goods/remove', this.saveForm.goodsImg,{
        headers: {
          'Content-Type': 'application/json; charset=utf-8' // 设置请求头，确保以正确的编码发送数据
        }})
          .then((result) => {
            result = result.data;
            if (result.success) {
              this.$message({
                message: result.message,
                type: 'success'
              });
            } else {
              this.$message({
                message: result.message,
                type: 'error'
              });
            }
            this.getGoods();
          });
    },
    //图片上传
    handleSuccess(response, file, fileList){
      // console.log(response);
      this.saveForm.imgurl = response;
    },
    handlePreview(file) {
      // console.log('1')
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },

    //全选按钮
    handleCheckAllChange(val) {
      this.EmployeeRole.roleId = val ? this.allRoleIds : []
      this.isIndeterminate = false;
    },

    // 处理选择事件
    handleCheck() {
      // 获取已选中的长度
      let checkedLength = this.EmployeeRole.roleId.length;
      // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
      this.checkAll = checkedLength === this.allRoleIds.length;
      // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
      this.isIndeterminate = checkedLength > 0 && checkedLength < this.allRoleIds.length;
    },

    // 搜索
    search() {
      // 设置query.currengPage为1,当进行搜索时,从第一页开始重新进行搜索
      this.query.currentPage = 1;
      //调用查询
      this.getPoster();
    },

    handleSizeChange(val) {
      this.query.pageSize = val;
      this.query.currentPage = 1;
      //查询结果
      this.getPoster();
    },

    handleCurrentChange(val) {
      // val为当前页，赋值后重新进行查询
      this.query.currentPage = val;
      // 调用查询方法
      this.getPoster();
    },

    // 获取用户反馈列表
    getPoster() {
      this.$http.post("/poster", this.query)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.pageInfo = result.resultObj;
              console.log(this.pageInfo)
            } else {
              this.$message({message: result.message, type: 'error'});
            }
          })
          .catch(result => {

          })
    },

    // 用户删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/poster/" + row.id)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({message: '删除成功', type: 'success'});
                //删除成功后回到第一页
                this.query.currentPage = 1;
                // 删除成功,要重新刷新该页面，调用方法查询
                this.getPoster();
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            })
            .catch(result => {
              this.$message({message: '很抱歉，网络有误', type: 'error'});
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },

    // 显示修改界面(回显数据)
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      this.saveForm.type = "";
      //调用方法让下拉框有值
      // this.getPoster();
    },

    // 显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id:null,
        type:'',
        imgurl: "",
      };
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //提交
    saveSubmit: function (addForm) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            var para = this.saveForm;
            this.$http.put("/poster/", para)
                .then(result => {
                  result = result.data;
                  if (result.success) {
                    //从第一页开始展示
                    this.query.currentPage = 1;
                    this.getPoster();
                    //关闭加载框
                    this.addLoading = false;
                    //关闭弹框
                    this.saveFormVisible = false;
                    this.$message({message: result.message, type: 'success'});
                  } else {
                    this.$message({message: result.message, type: 'error'});
                  }
                }).catch(result => {
              this.$message({message: result.message, type: 'error'});
            })
          });
        }
      });
    },

    // 批量删除员工
    batchRemove: function () {
      //遍历选中的sels数组的id值给ids
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 调用批量删除接口
        this.$http.patch("/poster", ids)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({message: '批量删除成功!', type: 'success'});
                //删除后回到第一页
                this.query.currentPage = 1;
                //调用查询
                this.getPoster();
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            })
      }).catch(() => {
        this.$message({message: "网络错误", type: 'error'});
      });
    }
  },

  mounted() {
    // 钩子函数，页面加载后，调用此方法，加载部门
    this.getPoster();
  }
}

</script>

<style scoped>

</style>
